package com.school.sports.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 数据库连接检查工具类
 * 用于在系统启动时检查数据库连接状态
 *
 * @author 系统开发团队
 * @since 2025-10-14
 */
@Slf4j
@Component
@Order(1)
public class DatabaseConnectionUtil implements CommandLineRunner {

    @Autowired
    private DataSource dataSource;

    @Override
    public void run(String... args) throws Exception {
        log.info("开始检查数据库连接状态...");

        try {
            checkDatabaseConnection();
            log.info("数据库连接检查完成，连接正常");
        } catch (Exception e) {
            log.error("数据库连接检查失败：{}", e.getMessage());
            // 这里不阻止应用启动，只记录错误日志
            log.warn("系统将继续启动，但数据库相关功能可能不可用");
        }
    }

    /**
     * 检查数据库连接
     *
     * @throws SQLException 当数据库连接失败时抛出
     */
    public void checkDatabaseConnection() throws SQLException {
        try (Connection connection = dataSource.getConnection()) {
            if (connection != null && !connection.isClosed()) {
                log.info("数据库连接成功 - 数据库URL: {}", connection.getMetaData().getURL());
                log.info("数据库产品信息: {} {}",
                    connection.getMetaData().getDatabaseProductName(),
                    connection.getMetaData().getDatabaseProductVersion());

                // 测试简单查询
                try {
                    connection.createStatement().execute("SELECT 1");
                    log.info("数据库查询测试通过");
                } catch (SQLException e) {
                    log.error("数据库查询测试失败: {}", e.getMessage());
                    throw e;
                }
            } else {
                throw new SQLException("数据库连接为空或已关闭");
            }
        }
    }

    /**
     * 获取数据库连接状态
     *
     * @return 连接状态信息
     */
    public String getDatabaseStatus() {
        try (Connection connection = dataSource.getConnection()) {
            if (connection != null && !connection.isClosed()) {
                return "数据库连接正常 - " + connection.getMetaData().getURL();
            }
        } catch (SQLException e) {
            log.error("获取数据库状态失败: {}", e.getMessage());
            return "数据库连接失败: " + e.getMessage();
        }
        return "数据库状态未知";
    }
}